# -*- coding: utf-8 -*-
import os
import re
import json
import urllib

from base import mcLogger
from base import mcScrapper
from base import mcDown
		
class uploadedtoDown(mcDown):

	@classmethod
	def exist_file(self, url):
		
		out = mcScrapper.get(url)
		m = re.search('id="filename"', out)
		#print out
		if m :
			return True
		
		return False

	
	def run(self, url, output_file):
		
		print "Uploadedto\n"
		
		if not self.exist_file(url):
			print "File not exist"
			return False 		
		
		
		logger = mcLogger.getInstance('uploadedto')

		cookies_file = "cookies/uploadedto"	
		
		os.system("rm -f " + cookies_file)		
		
		out = mcScrapper.get(url, cookies_file)
		m = re.search('<a href="file/([^"]*)', out)
		#print out
		id=0
		if m :
			id = m.group(1)
		else:
			print "File id not found"
			return False 				

		delay = 0
		m = re.search('waiting period: <span>([^<]*)</span>', out.replace('\n', ' '))
		if m :
			delay = m.group(1)

		print "Delay Found : %s \n" % delay

		if delay > 0:
			self.wait(delay)


		captcha_key = "6Lcqz78SAAAAAPgsTYF3UlGf2QFQCNuPMenuyHF3"

		data = {
			'ajax': "1"
			, 'cachestop': '0.5060976871241946'
			, 'k': captcha_key
			}

		post = urllib.urlencode(data)		
		
		ajax_url = "http://uploaded.to/io/ticket/slot/" + id
		
		print "Url : %s \n" % ajax_url		
		
		headers = { 'X-Requested-With' : 'XMLHttpRequest',
					'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
					'Referer' : url,
					'Accept' : 'text/javascript, text/html, application/xml, text/xml, */*',
					'Connection' : 'keep-alive',
					'Host' : 'uploaded.to'
					#,'Content-Length' :	'0'		
					,'X-Prototype-Version' : '1.6.1'					
					}			
				
		out = mcScrapper.post(ajax_url, post, cookies_file, headers)
		#print out
		
		if not '{succ:true}' == out:
			print "Some error"
			return False
		else:
			print "Result true"	
				
			jout = []
			while True:
					
				post =  mcDown.reCaptcha( captcha_key, cookies_file)			

				ajax_url = "http://uploaded.to/io/ticket/captcha/" + id
				
				print "Url : %s \n" % ajax_url
	
				headers = { 'X-Requested-With' : 'XMLHttpRequest'
							,'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
							,'Referer' : url
							,'Accept' : 'text/javascript, text/html, application/xml, text/xml, */*'
							#,'Connection' : 'keep-alive'
							,'Host' : 'uploaded.to'
							#,'Content-Length' :	'225'		
							,'X-Prototype-Version' : '1.6.1'					
							}				
				
				out = mcScrapper.post(ajax_url, post, cookies_file, headers)
							
				if not '{"err":"captcha"}' == out:
					print "Captcha Again"
					break


			if '{"err":"limit-dl"}' == out:				
				print "Download limit"
				return False


			m = re.search("url:'([^']*)", out)
			if m :			
				surl = m.group(1)
				
				os.system("wget '" + surl + "' -O '" + output_file + "'") 
				
				print "Download Success"
				return True


			print "Some error"
			return False
	
	
#			if '{"err":"limit-dl"}' == out:
#				print "Download limit"
#				return False
#	
#			print out

			#print "Url: %s" % out['url']			
			#print "Out: %s" % out['str']
		

			
"""		
http://wiki.xbmc.org/index.php?title=Adding_videos_to_the_library/Naming_files/TV_shows
"""
